import { ref, reactive, computed } from 'vue'
import { getTeacherOfSubject, getReviewerList, saveReviewSettings, getReviewDetail
  ,getSubjects,saveSubject

 } from '@/api/server/exam'
import { getExamReviewProgress } from '@/api/server/taskMange'
/**
 * 批阅设置Hook
 * @param {Object} options 配置参数
 * @param {Array} options.examList 考试列表引用
 * @returns {Object} 包含批阅设置相关的状态和方法
 */
export default function useReviewSetting({ examList }) {
  // 批阅设置对话框
  const dialogVisible = ref(false)
  const activeTab = ref('reviewers')
  const currentExam = ref(null)
  
  // 教师和批阅人员
  const teacherList = ref([])
  const teacherSearchKeyword = ref('')
  const selectedTeachers = ref([])
  const assignedReviewers = ref([])
  const selectedReviewers = ref([])
  
  // 批阅查询对话框
  const queryDialogVisible = ref(false)
  const reviewersList = ref([])
  
  // 批阅进度对话框
  const progressDialogVisible = ref(false)
  const reviewersProgress = ref([])
  const reviewerSearchKeyword = ref('')
  
  // 任务分配表单
  const assignmentForm = reactive({
    strategy: '1', // 默认选择整张试卷
  })
  
  // 每个评阅人分配的试卷数量
  const reviewerAssignments = ref([])
  
  // 时限设置表单
  const timeSettingsForm = reactive({
    startTime: '',
    endTime: '',
    enableReminder: 0,
    reminderTime: '6',
  })
  
  // 可用的提醒时间选项
  const availableReminderTimes = computed(() => {
    // 计算开始时间和结束时间之间的小时差
    let hoursDiff = 24; // 默认值
    
    if (timeSettingsForm.startTime && timeSettingsForm.endTime) {
      const start = new Date(timeSettingsForm.startTime);
      const end = new Date(timeSettingsForm.endTime);
      hoursDiff = Math.floor((end - start) / (60 * 60 * 1000));
    }
    
    return [
      { label: '提前1小时', value: '1', disabled: hoursDiff <= 1 },
      { label: '提前3小时', value: '3', disabled: hoursDiff <= 3 },
      { label: '提前6小时', value: '6', disabled: hoursDiff <= 6 },
      { label: '提前12小时', value: '12', disabled: hoursDiff <= 12 },
      { label: '提前1天', value: '24', disabled: hoursDiff <= 24 }
    ];
  });
  
  // 禁用开始日期（不能选择过去的日期）
  const disabledStartDate = (time) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    return time.getTime() < now.getTime();
  };
  
  // 禁用开始时间（今天之内不能选择过去的时间）
  const disabledStartTime = (time) => {
    const now = new Date();
    const selectedDate = new Date(timeSettingsForm.startTime);
    
    // 如果是今天，则不能选择过去的时间
    if (selectedDate.setHours(0, 0, 0, 0) === now.setHours(0, 0, 0, 0)) {
      const currentHour = new Date().getHours();
      const currentMinute = new Date().getMinutes();
      
      return {
        hours: (h) => h < currentHour,
        minutes: (m, hour) => hour === currentHour && m < currentMinute
      };
    }
    
    return {
      hours: () => false,
      minutes: () => false
    };
  };
  
  // 禁用结束日期（不能早于开始日期）
  const disabledEndDate = (time) => {
    if (!timeSettingsForm.startTime) {
      return disabledStartDate(time); // 如果没有开始时间，至少不能选今天之前的
    }
    
    const startDate = new Date(timeSettingsForm.startTime);
    startDate.setHours(0, 0, 0, 0);
    return time.getTime() < startDate.getTime();
  };
  
  // 禁用结束时间（不能早于开始时间）
  const disabledEndTime = (time) => {
    if (!timeSettingsForm.startTime) {
      return disabledStartTime(time);
    }
    
    const startTime = new Date(timeSettingsForm.startTime);
    const selectedDate = new Date(timeSettingsForm.endTime);
    
    // 如果选择的是同一天，则结束时间必须大于开始时间
    if (selectedDate.setHours(0, 0, 0, 0) === startTime.setHours(0, 0, 0, 0)) {
      const startHour = new Date(timeSettingsForm.startTime).getHours();
      const startMinute = new Date(timeSettingsForm.startTime).getMinutes();
      
      return {
        hours: (h) => h < startHour,
        minutes: (m, hour) => hour === startHour && m <= startMinute
      };
    }
    
    return {
      hours: () => false,
      minutes: () => false
    };
  };
  
  // 开始时间变更时触发验证
  const handleStartTimeChange = () => {
    // 如果结束时间早于开始时间，则清空结束时间
    if (timeSettingsForm.endTime && timeSettingsForm.startTime >= timeSettingsForm.endTime) {
      timeSettingsForm.endTime = '';
    }
    
    // 如果开启了提醒，验证提醒时间
    if (timeSettingsForm.enableReminder) {
      validateReminderTime();
    }
  };
  
  // 验证时间范围
  const validateTimeRange = () => {
    if (timeSettingsForm.startTime && timeSettingsForm.endTime) {
      const start = new Date(timeSettingsForm.startTime);
      const end = new Date(timeSettingsForm.endTime);
      
      // 结束时间必须晚于开始时间
      if (start >= end) {
        ElMessage.warning('批阅截止时间必须晚于开始时间');
        timeSettingsForm.endTime = '';
        return false;
      }
      
      // 如果启用提醒，验证提醒时间是否合理
      if (timeSettingsForm.enableReminder) {
        validateReminderTime();
      }
    }
    return true;
  };
  
  // 验证提醒时间
  const validateReminderTime = () => {
    if (!timeSettingsForm.enableReminder || !timeSettingsForm.startTime || !timeSettingsForm.endTime) {
      return true;
    }
    
    const start = new Date(timeSettingsForm.startTime);
    const end = new Date(timeSettingsForm.endTime);
    const hoursDiff = Math.floor((end - start) / (60 * 60 * 1000));
    
    // 如果时间范围小于提醒时间，自动选择一个合适的提醒时间
    if (hoursDiff <= Number(timeSettingsForm.reminderTime)) {
      const availableOption = availableReminderTimes.value.find(option => !option.disabled);
      if (availableOption) {
        timeSettingsForm.reminderTime = availableOption.value;
        ElMessage.info(`由于批阅时间范围较短，已将提醒时间调整为${availableOption.label}`);
      } else {
        timeSettingsForm.enableReminder = false;
        ElMessage.warning('批阅时间范围过短，无法设置提醒');
      }
    }
    
    return true;
  };
  
  // 获取时间范围信息
  const getTimeRangeInfo = () => {
    if (!timeSettingsForm.startTime || !timeSettingsForm.endTime) {
      return '';
    }
    
    const start = new Date(timeSettingsForm.startTime);
    const end = new Date(timeSettingsForm.endTime);
    const diffMs = end - start;
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffHours / 24);
    
    if (diffDays > 0) {
      return `批阅时间共 ${diffDays} 天 ${diffHours % 24} 小时`;
    } else {
      return `批阅时间共 ${diffHours} 小时`;
    }
  };
  
  // 过滤后的教师列表
  const filteredTeachers = computed(() => {
    if (!teacherSearchKeyword.value) {
      return teacherList.value.filter(teacher => 
        !assignedReviewers.value.some(reviewer => reviewer.account === teacher.account)
      )
    }
    return teacherList.value.filter(teacher => 
      !assignedReviewers.value.some(reviewer => reviewer.account === teacher.account) &&
      (teacher.name.toLowerCase().includes(teacherSearchKeyword.value.toLowerCase()) ||
      teacher.account.toLowerCase().includes(teacherSearchKeyword.value.toLowerCase()))
    )
  })
  
  // 过滤后的批阅教师进度列表
  const filteredReviewersProgress = computed(() => {
    if (!reviewerSearchKeyword.value) {
      return reviewersProgress.value
    }
    
    return reviewersProgress.value.filter(reviewer => 
      reviewer.name.toLowerCase().includes(reviewerSearchKeyword.value.toLowerCase()) ||
      reviewer.account.toLowerCase().includes(reviewerSearchKeyword.value.toLowerCase())
    )
  })
  
  // 获取不同状态的样式类型
  const getStatusType = (status) => {
    switch (status) {
      case '待分配':
        return 'info'
      case '批阅中':
        return 'warning'
      case '已批阅':
        return 'success'
      default:
        return ''
    }
  }
  
  // 获取进度百分比
  const getProgressPercentage = (reviewer) => {
    if (!reviewer.detailCount) return 0
    return Math.round((reviewer.doneCount/ reviewer.detailCount) * 100)
  }
  
  // 获取进度状态
  const getProgressStatus = (reviewer) => {
    const percentage = getProgressPercentage(reviewer)
    if (percentage === 100) return 'success'
    if (percentage >= 80) return 'warning'
    return 'exception'
  }
  
  // 获取完成率文本
  const getCompletionRate = (reviewer) => {
    const percentage = getProgressPercentage(reviewer)
    return `${percentage}%`
  }
  
  // 获取总体进度百分比
  const getOverallPercentage = () => {
    if (!reviewersProgress.value || !reviewersProgress.value.total) return 0
    
    // 使用reviewersProgress.value.total和reviewersProgress.value.doneTotal直接计算进度
    return reviewersProgress.value.total ? 
      Math.round((reviewersProgress.value.doneTotal / reviewersProgress.value.total) * 100) : 0
  }
  
  // 获取总体进度状态
  const getOverallStatus = () => {
    const percentage = getOverallPercentage()
    if (percentage === 100) return 'success'
    if (percentage >= 80) return 'warning'
    return 'exception'
  }
  
  // 百分比格式化
  const percentageFormat = (percentage) => {
    return `${percentage}% 完成`
  }
  
  // 获取教师的进度状态文本
  const getProgressStatusText = (reviewer) => {
    const percentage = getProgressPercentage(reviewer)
    if (percentage === 100) {
      return '已完成'
    } else if (percentage >= 70) {
      return '进度良好'
    } else if (percentage >= 30) {
      return '正常进度'
    } else {
      return '进度缓慢'
    }
  }
  
  // 获取教师的进度状态样式类
  const getProgressStatusClass = (reviewer) => {
    const percentage = getProgressPercentage(reviewer)
    if (percentage === 100) {
      return 'excellent'
    } else if (percentage >= 50) {
      return 'good'
    } else {
      return 'slow'
    }
  }
  
  
  
  
  // 获取教师列表
  const fetchTeachers = async () => {
    if (!currentExam.value || !currentExam.value.subjectId) {
      ElMessage.warning('无法获取学科信息')
      return
    }
    
    try {
      const response = await getTeacherOfSubject(currentExam.value.subjectId)
      
      if (response.data && response.data.code === 200) {
        // 将返回的教师数据映射为组件需要的格式
        teacherList.value = (response.data.data.list || []).map(teacher => ({
          id: teacher.id, // 保存教师ID
          account: teacher.account,
          name: teacher.name
        }))
      } else {
        // 处理接口返回的错误
        ElMessage.error(response.data?.message || '获取教师列表失败')
      }
    } catch (error) {
      console.error('获取教师列表失败', error)
      ElMessage.error('获取教师列表失败')
    }
  }
  
  // 获取策略描述文本
  const getStrategyDescription = (strategy) => {
    switch (strategy) {
      case '1':
        return '教师将批阅完整的试卷，每位教师会被分配若干完整试卷进行随机批阅。系统将自动平均分配试卷给所有批阅人员。'
      case '2':
        return '教师将按题型批阅试卷，每位教师只批阅所分配题型的所有试卷。系统会将大题随机分配给教师批阅，确保工作量相对均衡。'
      default:
        return ''
    }
  }
  
  // 获取预计总试卷数
  const getTotalEstimatedPapers = () => {
    // 模拟总试卷数，实际应从考试数据中获取
    return currentExam.value?.paperCount || 100
  }
  

  
  // 获取分配信息提示
  const getAssignmentMessage = () => {
    if (assignedReviewers.value.length === 0) {
      return '请先在批阅人员设置中添加批阅教师'
    }
    
    if (assignmentForm.strategy === '1') {
      return `系统将随机分配试卷，每位教师将批阅完整试卷，预计每人 ${getEstimatedPapersPerPerson()} 份`
    } else {
      return '系统将按题型随机分配，每位教师将负责所有试卷的部分题型批阅'
    }
  }
  

  
  
  // 打开批阅设置对话框
  const openReviewSetting = (row) => {
    currentExam.value = row
    
    assignedReviewers.value = []
    selectedTeachers.value = []
    selectedReviewers.value = []
    reviewerAssignments.value = []
    
    // 重置表单
    assignmentForm.strategy = '1'
    timeSettingsForm.startTime = ''
    timeSettingsForm.endTime = ''
    timeSettingsForm.enableReminder = false
    timeSettingsForm.reminderTime = '6'
    
    dialogVisible.value = true
    
    // 获取该学科的教师列表
    fetchTeachers()
  }
  
  // 当考试状态为 已批阅时，点击 "查看详情"触发
  const reviewDetailResult = ref([])
  const openReviewQuery = async (row) => {
    currentExam.value = row
    
    try {
      // 这里应该是调用getReviewerList接口获取批阅教师列表
      const response = await getReviewDetail(row.id)
      reviewDetailResult.value = response.data.data
      queryDialogVisible.value = true
    } catch (error) {
      console.error('获取批阅教师列表失败', error)
      ElMessage.error('获取批阅教师列表失败')
      
 
    }
  }

// 获取批阅进度
const fetchReviewerProgress = async (row) => {
  try {
    const response = await getExamReviewProgress({ examId: row.id })
  
    if (response.data.code === 200) {
      reviewersProgress.value = response.data.data
      reviewersProgress.value.exam = row  
    } else {
      ElMessage.error(response.data?.message || '获取批阅进度失败')
    }
  } catch (error) {
    console.error('获取批阅进度失败', error)
    ElMessage.error('获取批阅进度失败')
  }
}

  // 打开批阅进度对话框
  const handleReviewProgress = async (row) => {
    currentExam.value = row
    await fetchReviewerProgress(row)
    progressDialogVisible.value = true
  }


// 刷新进度数据
const refreshProgress = async () => {
    
  try {
 
  
    
    // 模拟API调用延迟
    await fetchReviewerProgress(reviewersProgress.value.exam)
    
  
    
    ElMessage.success('数据已刷新')
  } catch (error) {
    console.error('刷新进度数据失败', error)
    ElMessage.error('刷新数据失败')
  }
}

  
  // 选择教师
  const handleSelectionChange = (selection) => {
    selectedTeachers.value = selection
  }
  
  // 选择已添加的批阅人员
  const handleReviewerSelectionChange = (selection) => {
    selectedReviewers.value = selection
  }
  
  // 添加选中教师到批阅人员
  const addSelectedTeachers = () => {
    if (selectedTeachers.value.length === 0) return
    
    assignedReviewers.value = [
      ...assignedReviewers.value,
      ...selectedTeachers.value.filter(teacher => 
        !assignedReviewers.value.some(reviewer => reviewer.account === teacher.account)
      )
    ]
    
    // 为新添加的教师创建任务分配记录
    reviewerAssignments.value = assignedReviewers.value.map((reviewer, index) => {
      const existing = reviewerAssignments.value.find(item => item.account === reviewer.account)
      return existing || { id: reviewer.id, account: reviewer.account, count: 0 }
    })
    
    selectedTeachers.value = []
  }
  
  // 移除选中的批阅人员
  const removeSelectedReviewers = () => {
    if (selectedReviewers.value.length === 0) return
    
    // 移除选中的批阅人员
    assignedReviewers.value = assignedReviewers.value.filter(reviewer => 
      !selectedReviewers.value.some(selected => selected.account === reviewer.account)
    )
    
    // 更新任务分配记录
    reviewerAssignments.value = assignedReviewers.value.map((reviewer, index) => {
      const existing = reviewerAssignments.value.find(item => item.account === reviewer.account)
      return existing || { id: reviewer.id, account: reviewer.account, count: 0 }
    })
    
    selectedReviewers.value = []
  }
  
  // 验证批阅设置
  const validateSettings = () => {
    // 检查是否有批阅人员的逻辑已经移至组件中，此处跳过该检查
    
    // 检查是否设置了批阅策略
    if (!assignmentForm.strategy) {
      ElNotification({
        title: '温馨提醒',
        message: '请选择批阅任务分配方式',
        type: 'warning',
        duration: 4000,
        position: 'top-right',
        zIndex: 9999
      })
      activeTab.value = 'assignment'
      return false
    }
  
    
    // 检查时间设置
    if (!timeSettingsForm.startTime) {
      ElNotification({
        title: '温馨提醒',
        message: '请设置批阅开始时间',
        type: 'warning',
        duration: 4000,
        position: 'top-right',
      })
      activeTab.value = 'timeSettings'
      return false
    }
    
    if (!timeSettingsForm.endTime) {
      ElNotification({
        title: '温馨提醒',
        message: '请设置批阅截止时间',
        type: 'warning',
        duration: 4000,
        position: 'top-right',
      })
      activeTab.value = 'timeSettings'
      return false
    }
    
    const now = new Date();
    const startTime = new Date(timeSettingsForm.startTime);
    
    // 验证开始时间不能早于当前时间
    if (startTime < now) {
      ElNotification({
        title: '温馨提醒',
        message: '批阅开始时间不能早于当前时间',
        type: 'warning',
        duration: 4000,
        position: 'top-right',
      })
      activeTab.value = 'timeSettings'
      return false
    }
    
    // 验证结束时间必须晚于开始时间
    if (timeSettingsForm.startTime >= timeSettingsForm.endTime) {
   
      ElMessage({
        message: '批阅截止时间必须晚于开始时间',
        type: 'warning',
      })
      activeTab.value = 'timeSettings'
      return false
    }
    
    // 如果启用了提醒，验证提醒时间是否合理
    if (timeSettingsForm.enableReminder) {
      const start = new Date(timeSettingsForm.startTime);
      const end = new Date(timeSettingsForm.endTime);
      const hoursDiff = Math.floor((end - start) / (60 * 60 * 1000));
      
      if (hoursDiff <= Number(timeSettingsForm.reminderTime)) {
        ElNotification({
          title: '温馨提醒',
          message: '提醒时间必须在批阅时间范围内',
          type: 'warning',
          duration: 4000,
          position: 'top-right',
          zIndex: 9999
        })
        activeTab.value = 'timeSettings'
        return false
      }
    }
    
    return true
  }
  
  // 保存批阅设置
  const saveSettings = async () => {
    
    if (!validateSettings()) return false
    
    try {
      // 确认保存
      await ElMessageBox({
        title: ' ',
        message: `
          <div style="padding: 0; max-width: 520px; margin: 0 auto; font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;">
            <div style="background-color: #fff; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1); overflow: hidden;">
              <div style="padding: 15px; text-align: center; background-color: #f5f7fa; border-bottom: 1px solid #ebeef5;">
                <p style="font-size: 16px; margin: 0; color: #303133; font-weight: 500;">您确定要保存以下批阅设置吗？</p>
              </div>
              <div style="padding: 20px;">
                <div style="background-color: #f8f9fb; padding: 15px; border-radius: 6px; margin-bottom: 15px;">
                  <div style="margin-bottom: 12px; display: flex; align-items: center;">
                    <span style="color: #409EFF; margin-right: 8px; font-size: 16px;">👥</span>
                    <span style="color: #606266;">批阅人员: <span style="color: #303133; font-weight: 500;">${assignedReviewers.value.length} 名教师</span></span>
                  </div>
                  <div style="margin-bottom: 12px; display: flex; align-items: center;">
                    <span style="color: #409EFF; margin-right: 8px; font-size: 16px;">⚙️</span>
                    <span style="color: #606266;">分配策略: <span style="color: #303133; font-weight: 500;">${assignmentForm.strategy === '1' ? '整卷批阅' : '按题型批阅'}</span></span>
                  </div>
                  <div style="margin-bottom: 12px; display: flex; align-items: center;">
                    <span style="color: #409EFF; margin-right: 8px; font-size: 16px;">🕒</span>
                    <span style="color: #606266;">批阅时间: <span style="color: #303133; font-weight: 500;">${new Date(timeSettingsForm.startTime).toLocaleString()} - ${new Date(timeSettingsForm.endTime).toLocaleString()}</span></span>
                  </div>
                  <div style="display: flex; align-items: center;">
                    <span style="color: #409EFF; margin-right: 8px; font-size: 16px;">🔔</span>
                    <span style="color: #606266;">提醒设置: <span style="color: #303133; font-weight: 500;">${timeSettingsForm.enableReminder ? `提前 ${timeSettingsForm.reminderTime} 小时` : '未启用'}</span></span>
                  </div>
                </div>
                <div style="text-align: center; color: #909399; font-size: 12px; margin-bottom: 20px;">
                  <p style="margin: 0;">点击"确认保存"后系统将开始批阅任务</p>
                </div>
                <div style="display: flex; justify-content: center; gap: 20px; padding-top: 5px;">
                  <button 
                    type="button" 
                    class="cancel-btn" 
                    onclick="document.querySelector('.el-message-box__close').click()"
                    style="
                      padding: 9px 20px; 
                      border-radius: 20px; 
                      background-color: #ffffff;
                      color: #606266; 
                      border: 1px solid #dcdfe6;
                      font-size: 14px;
                      cursor: pointer;
                      font-weight: 500;
                      transition: all 0.3s;
                      outline: none;
                    "
                    onmouseover="this.style.backgroundColor='#f5f7fa'; this.style.transform='translateY(-2px)'; this.style.boxShadow='0 2px 8px rgba(0, 0, 0, 0.1)';"
                    onmouseout="this.style.backgroundColor='#ffffff'; this.style.transform='translateY(0)'; this.style.boxShadow='none';"
                  >返回修改</button>
                  <button 
                    type="button" 
                    class="confirm-btn" 
                    onclick="document.querySelector('.el-message-box__btns .el-button--primary').click()"
                    style="
                      padding: 9px 20px; 
                      border-radius: 20px; 
                      background-color: #409EFF;
                      color: #ffffff; 
                      border: 1px solid #409EFF;
                      font-size: 14px;
                      cursor: pointer;
                      font-weight: 500;
                      transition: all 0.3s;
                      outline: none;
                    "
                    onmouseover="this.style.backgroundColor='#66b1ff'; this.style.borderColor='#66b1ff'; this.style.transform='translateY(-2px)'; this.style.boxShadow='0 2px 8px rgba(0, 0, 0, 0.1)';"
                    onmouseout="this.style.backgroundColor='#409EFF'; this.style.borderColor='#409EFF'; this.style.transform='translateY(0)'; this.style.boxShadow='none';"
                  >确认保存</button>
                </div>
              </div>
            </div>
          </div>
        `,
        dangerouslyUseHTMLString: true,
        showCancelButton: true,
        showConfirmButton: true,
        confirmButtonText: '确认保存',
        cancelButtonText: '返回修改',
        confirmButtonClass: 'confirm-hidden-btn',
        cancelButtonClass: 'cancel-hidden-btn',
        customClass: 'review-confirm-dialog custom-buttons-dialog',
        distinguishCancelAndClose: true,
        closeOnClickModal: false,
        center: true,
        roundButton: true,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            // 在这里可以处理确认保存按钮的点击事件
            done(); // 关闭弹窗
          } else {
            // 处理取消或关闭情况
            done(); // 直接关闭弹窗
          }
        }
      })
      
      // 检查所有批阅人员是否都有ID
      const missingIdReviewers = assignedReviewers.value.filter(reviewer => !reviewer.id)
      if (missingIdReviewers.length > 0) {
        ElMessage.error(`有${missingIdReviewers.length}名批阅人员缺少ID信息，无法保存`)
        return false
      }
      
      // 构建请求参数
      const payload = {
        examId: currentExam.value.id,
        reviewers: assignedReviewers.value.map(reviewer => reviewer.id), // 使用教师ID而不是账号
        assignmentStrategy: parseInt(assignmentForm.strategy),
        startTime: timeSettingsForm.startTime,
        endTime: timeSettingsForm.endTime,
        enableReminder: timeSettingsForm.enableReminder ? 1 : 0,
        remindHourBefore: timeSettingsForm.enableReminder ? Number(timeSettingsForm.reminderTime) : null,
      }
      
      // 调用保存批阅设置接口
      const response = await saveReviewSettings(payload)
      
      // 处理响应
      if (response?.data?.code === 200) {
        ElMessage({
          message: '批阅任务分配成功！',
          type: 'success',
        })
        dialogVisible.value = false
        
        // 更新当前考试的批阅状态
        const index = examList.value.findIndex(exam => exam.id === currentExam.value.id)
        if (index !== -1) {
          examList.value[index].reviewStatus = true
          // 改为批阅中状态而不是已批阅
          examList.value[index].examinationStatus = '批阅中'
        }
       
        return true
      } else {
        // 处理接口返回的错误
        ElMessage.error(response?.data?.message || '保存批阅设置失败')
        return false
      }
    } catch (error) {
      // 用户取消操作或API错误
      if (error !== 'cancel') {
        ElMessage.error('保存批阅设置失败')
      }
      return false
    }
  }
  
  

  // 获取本场考试涉及的所有主观题
  const subjects = ref([])
  const selectedExamId = ref(null)
  const getSubjectsOfHook = async () => {
    const response = await getSubjects({examinationId:selectedExamId.value})
    subjects.value = response?.data?.data
    console.log('subjects: ',subjects.value)
  }
  const settingDialogVisible = ref(false)
  const openSetting =async (row) => {
    selectedExamId.value = row.id
    await getSubjectsOfHook()
    settingDialogVisible.value = true
  }

  // 保存主观题参考答案
  const saveSubjectOfHook = async (subject) => {
    const response = await saveSubject({answerId:subject.answerId, gradingRules:subject.gradingRules})
    if(response?.data?.code === 200){
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
    }else{
      ElMessage.error(response?.data?.message || '保存失败')
    }
  }


  return {
    // 状态
    dialogVisible,
    activeTab,
    currentExam,
    teacherList,
    teacherSearchKeyword,
    selectedTeachers,
    assignedReviewers,
    selectedReviewers,
    assignmentForm,
    reviewerAssignments,
    timeSettingsForm,
    filteredTeachers,
    queryDialogVisible,
    reviewersList,
    progressDialogVisible,
    reviewersProgress,
    reviewerSearchKeyword,
    filteredReviewersProgress,
    availableReminderTimes,
    reviewDetailResult, 
    // 方法
    fetchTeachers,
    openReviewSetting,
    openReviewQuery,
    handleReviewProgress,
    handleSelectionChange,
    handleReviewerSelectionChange,
    addSelectedTeachers,
    removeSelectedReviewers,
    saveSettings,
    refreshProgress,
    getStrategyDescription,
    getTotalEstimatedPapers,
    getAssignmentMessage,
    
    // 时间验证相关
    disabledStartDate,
    disabledStartTime,
    disabledEndDate,
    disabledEndTime,
    handleStartTimeChange,
    validateTimeRange,
    validateReminderTime,
    getTimeRangeInfo,
    
    // 工具方法
    getStatusType,
    getProgressPercentage,
    getProgressStatus,
    getCompletionRate,
    getOverallPercentage,
    getOverallStatus,
    percentageFormat,
    getProgressStatusText,
    getProgressStatusClass,

    // 获取本场考试涉及的所有主观题
    subjects,
    openSetting,
    settingDialogVisible,

    // 保存主观题参考答案
    saveSubjectOfHook,
  }
} 